package com.gitee.ywj1352.zk.quickStart;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author wenjie.yang on 2019/6/19.
 */
public class QuickStart {

    //建立连接
    public static ZooKeeper  createConnection(){
        //防止 出现 没有连接成功
        ZooKeeper zk = null;
        try {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            zk=  new ZooKeeper("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183", 40000, watchedEvent ->{
                System.out.println(watchedEvent.getType()+"全局的默认事件");
                if (Watcher.Event.KeeperState.SyncConnected.equals(watchedEvent.getState())){
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return zk;
    }


    public static void crud(ZooKeeper zooKeeper){
        try {
            zooKeeper.create("/zk-persis-ywj", "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            Stat stat = new Stat();
            byte[] data = zooKeeper.getData("/zk-persis-ywj", null, stat);
            System.out.println(new String(data));
            //乐观锁 修改节点值
            zooKeeper.setData("/zk-persis-ywj","1".getBytes(),stat.getVersion());
            byte[] data2 = zooKeeper.getData("/zk-persis-ywj", null, stat);
            System.out.println(new String(data2));
            zooKeeper.delete("/zk-persis-ywj",stat.getVersion());

            zooKeeper.close();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) throws Exception{
        ZooKeeper connection = createConnection();
        crud(connection);
    }



}
